import cv2
import numpy as np
from flask import Flask, Blueprint, request
from util.register import fr
from werkzeug.utils import secure_filename
from util.http import fail_api, success_api

bp = Blueprint('face_recognize', __name__)

@bp.post('/register')
def register():
    # 1. 检查文件是否存在
    if 'img' not in request.files:
        return fail_api('未上传图片')

    img = request.files['img']

    if img:
        # 获取文件名（注意：要使用 secure_filename 防止路径遍历攻击）
        filename = secure_filename(img.filename)
    else:
        return fail_api('未能加载图片')

    # 确保 image 是 NumPy 数组
    file_bytes = img.read()  # 返回 bytes 数据
    np_array = np.frombuffer(file_bytes, np.uint8) # 返回 NumPy 数组
    img = cv2.imdecode(np_array, cv2.IMREAD_COLOR) # OpenCV 用于从内存缓冲区（如网络传输的字节流或 NumPy 数组）解码图像的函数

    if img is None:
        return fail_api('无效的图片格式')
    # 检查图片尺寸
    if img.size == 0:
        return fail_api('图片数据为空')

    #欧式距离
    # result = fr.register(img, filename)
    #余弦相似度
    result = fr.register_sim(img, filename)
    if result != "success":
        return result
    return success_api("注册成功：%s" % filename)

@bp.post('/recognition')
def recognition():
    if 'img' not in request.files:
        return fail_api("未上传图片")

    img = request.files['img']

    if img:
        filename = secure_filename(img.filename)
    else:
        return fail_api('未能加载图片')

    file_bytes = img.read()
    np_array = np.frombuffer(file_bytes, np.uint8)
    img = cv2.imdecode(np_array, cv2.IMREAD_COLOR)

    #欧式距离
    #results = fr.recognition_sim(img)
    #余弦相似度
    results = fr.recognition_sim(img)
    results = list(results)
    if len(results) < 1:
        return fail_api("未识别到人脸")
    else:
        return success_api("识别成功：%s" % results[0])
